<?php

namespace Biz\model\GoodsTestActivity;

use Biz\tools\BizUrl;
use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\ImgUrl;
use Medoo\Medoo;

class FineGoodsModel extends BaseDbModel
{

    public const _CONFIG_FILE_ = 'db_store';


    public const _CONFIG_SELECT_ = 'db_brand_activity';

    public const _DATABASE_ = 'brand_activity';


    public const _TABLE_NAME = 'fine_goods_test_activity';

    const CATEGORY_TAG_MAP = [
        0 => '全部',
        1 => '家具',
        2 => '日用',
        3 => '装饰',
        4 => '家电',
        5 => '灯饰建材',
        6 => '宠物',
    ];

    const TYPE_LIGHT_TEST = 1;//轻测
    const TYPE_UNBOX = 2;//开箱
    const TYPE_EVALUATION = 3;//评测
    const TYPE_EVALUATION_OLD = 4;//旧版评测

    const TYPE_MAP = [
        self::TYPE_LIGHT_TEST => '轻测',
        self::TYPE_UNBOX => '开箱',
        self::TYPE_EVALUATION => '测评',
        self::TYPE_EVALUATION_OLD => '旧版测评',
    ];
    //品牌后台以及品牌消息展示 好物轻测 用这个
    const TYPE_MAP_BACKUPS = [
        self::TYPE_LIGHT_TEST => '轻测',
        self::TYPE_UNBOX => '开箱',
        self::TYPE_EVALUATION => '评测',
        self::TYPE_EVALUATION_OLD => '旧版评测',
    ];

    const COUPON_LINK_TYPE_TB = 1;//优惠券链接类型：淘宝
    const COUPON_LINK_TYPE_JD = 2;//优惠券链接类型：京东

    const COUPON_LINK_MAP = [
        self::COUPON_LINK_TYPE_TB => '淘宝',
        self::COUPON_LINK_TYPE_JD => '京东',
    ];

    public const STATE_DEFAULT = 0;    //草稿

    public const STATE_WAIT = 1;    //待审核：品牌提交报名，但运营人员未对其做出审核操作（常态）

    public const STATE_NOT_PASS = 2;    //审核不通过：运营人员对其报名内容判定不合规或物料有问题，同时品牌侧后台右侧下发通知消息；

    public const STATE_PASS = 3;    //审核通过

    public const STATE_DEL = 9;//已删除


    //虚拟状态

    public const STATE_TO_BE_ONLINE = 4;    //待上线：运营人员对其审核通过，并确定具体排期；
    public const STATE_APPLYING = 5;    //活动申请中：可以理解为就是到达排期成功上线，默认7天内的时间为申请中，运营人员如过有需求在后台修改申请到期的日期，则按修改后的时间范围来；

    public const STATE_VERIFY = 6;    //名单审核中：申请日期结束-72小时内，为名单的审核日期；

    public const STATE_EXPERIENCING = 7;    //体验中：名单已经公布，直到第一篇体验报告被选中的阶段 / 名单已产出；
    public const STATE_OUTPUT_REPORT = 8;    //报告已产出：住友发布内容，且在审核后台被运营选出；

    public const STATE_JOIN = 10;//已申请

    public const VERIFY_USER_TIME = 3 * 24 * 3600;//申请日期结束-72小时内，为名单的审核日期
    public const ONE_DAY = 1 * 24 * 3600;

    public const ACTIVITY_STATE = [
        self::STATE_DEFAULT => "草稿",
        self::STATE_WAIT => "待审核",
        self::STATE_NOT_PASS => "审核不通过",
        self::STATE_PASS => "审核通过",
        self::STATE_TO_BE_ONLINE => "待上线",
        self::STATE_APPLYING => "申请中",
        self::STATE_VERIFY => "名单审核中",
        self::STATE_EXPERIENCING => "体验中/名单已产出",
        self::STATE_OUTPUT_REPORT => "报告已产出",
        self::STATE_DEL => '已取消',
    ];

    public const OPERATE_TYPE_ADMIN = 1;
    public const OPERATE_TYPE_USER = 2;

    public const PACKAGE_A = 1;
    public const PACKAGE_B = 2;
    public const PACKAGE_C = 3;
    public const PACKAGE_BUSINESS_COOPERATION = 11;

    public const PACKAGE_A_FREE_TIMES = 1;
    public const PACKAGE_B_FREE_TIMES = 1;
    public const PACKAGE_C_FREE_TIMES = 1;
    public const PACKAGE = [
        self::PACKAGE_A => 'A套餐',
        self::PACKAGE_B => 'B套餐',
        self::PACKAGE_C => 'C套餐',
        self::PACKAGE_BUSINESS_COOPERATION => '商业合作专属套餐',
    ];
    public const PACKAGE_FANS_GRADE_DEFAULT = 0;
    public const PACKAGE_FANS_GRADE_A = 1;
    public const PACKAGE_FANS_GRADE_B = 2;
    public const PACKAGE_FANS_GRADE_C = 3;
    public const PACKAGE_FANS_GRADE_D = 4;
    public const PACKAGE_FANS_GRADE_E = 5;
    public const PACKAGE_FANS_GRADE_F = 6;
    public const PACKAGE_FANS_GRADE_G = 7;
    public const PACKAGE_FANS_GRADE_H = 8;

    public const PACKAGE_FANS_GRADE_MAP = [
        self::PACKAGE_FANS_GRADE_DEFAULT => '149-0',
        self::PACKAGE_FANS_GRADE_A => '300-150',
        self::PACKAGE_FANS_GRADE_B => '500-301',
        self::PACKAGE_FANS_GRADE_C => '1000-501',
        self::PACKAGE_FANS_GRADE_D => '2000-1001',
        self::PACKAGE_FANS_GRADE_E => '3000-2001',
        self::PACKAGE_FANS_GRADE_F => '6000-3001',
        self::PACKAGE_FANS_GRADE_G => '10000-6001',
        self::PACKAGE_FANS_GRADE_H => '99999999-10001',
    ];

    public const PACKAGE_FANS_GRADE_DATA = [
        self::PACKAGE_A => [
            self::PACKAGE_FANS_GRADE_D => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_C => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_B => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_A => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_B => [
            self::PACKAGE_FANS_GRADE_E => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_D => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_C => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_B => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_A => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_C => [
            self::PACKAGE_FANS_GRADE_E => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_D => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_C => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_B => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_A => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_BUSINESS_COOPERATION => [
            self::PACKAGE_FANS_GRADE_E => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_D => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_C => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_B => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_A => self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
    ];

    public const PACKAGE_FANS_NUM = [
        self::PACKAGE_A => [
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_B => [
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_C => [
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
        self::PACKAGE_BUSINESS_COOPERATION => [
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_E],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_D],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_C],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_B],
            self::PACKAGE_FANS_GRADE_MAP[self::PACKAGE_FANS_GRADE_A],
        ],
    ];


    public static function selectList($where, $field = '*')
    {
        $result = [];
        $list = self::select($field, $where);
        if (is_array($field) || $field == '*') {
            foreach ($list as $row) {
                $info = self::formatInfo($row);
                $result[] = $info;
            }
        }

        return $result;
    }

    public static function formatInfo($info)
    {
        $now = time();
        foreach ($info as $key => $val) {
            switch ($key) {
                case 'activity_state':
                    switch ($val) {
                        case self::STATE_DEFAULT://草稿
                        case self::STATE_WAIT://待审核
                        case self::STATE_NOT_PASS://审核未通过
                        case self::STATE_DEL://已取消
                            break;
                        case self::STATE_PASS://审核通过
                            if ($now < $info['schedule_start_time'] || empty($info['schedule_start_time'])) {
                                $info['activity_state'] = self::STATE_TO_BE_ONLINE;//待上线
                            } else {
                                if ($now >= $info['schedule_start_time'] && $now < $info['schedule_end_time']) {
                                    $info['activity_state'] = self::STATE_APPLYING;//申请中
                                } else {
                                    if ($now >= $info['schedule_end_time'] && $now <= ($info['schedule_end_time'] + self::VERIFY_USER_TIME)) {
                                        $info['activity_state'] = self::STATE_VERIFY;//名单审核中
                                    } else {
                                        if ($now > ($info['schedule_end_time'] + self::VERIFY_USER_TIME)) {
                                            if ((int)$info['report_num'] === 0) {
                                                $info['activity_state'] = self::STATE_EXPERIENCING;//体验中/名单已产出
                                            } else {
                                                $info['activity_state'] = self::STATE_OUTPUT_REPORT;//报告已产出
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                    }
                    $info['activity_state_name'] = self::ACTIVITY_STATE[$info['activity_state']];
                    break;
                case 'cover_img':
                    $info['cover_img_url'] = $val ? ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_BIZ, $val,
                        ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
                    break;
                case 'advantage_img':
                    $advantageImg = $val ? json_decode($val, true) : [];
                    $info['advantage_img_id'] = $advantageImg;
                    $advantageImg = empty($advantageImg) ? [] : $advantageImg;
                    $info['advantage_img'] = [];
                    foreach ($advantageImg as $img) {
                        $info['advantage_img'][] = ImgUrl::getUrlNotSWater(ImgUrl::APPTYPE_BIZ, $img,
                            ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                    }

                    break;
                case 'advantage_text':
                    $advantageText = $val ? json_decode($val, true) : [];
                    $advantageText = $advantageText ?: [];
                    $info['advantage_text'] = $advantageText;
                    break;
                case 'desc_text':
                    $descText = $val ? json_decode($val, true) : [];
                    $descText = $descText ?: [];
                    $info['desc_text'] = $descText;
                    break;
                case 'package_combination':
                    $packageCombination = json_decode($val, true) ?? [];
                    $packageCombinationData = [];
                    $info['package_combination_name'] = '';
                    $i = 1;
                    foreach ($packageCombination as $item) {
                        $item['package_name'] = FineGoodsModel::PACKAGE[$item['package']];
                        if ($i == 1) {
                            $info['package_combination_name'] .= $item['package_name'];
                        } else {
                            $info['package_combination_name'] .= '+' . $item['package_name'];
                        }
                        $packageCombinationData[] = $item;
                        $i++;
                    }
                    $info['package_combination_data'] = $packageCombinationData;
                    break;
                case 'category_tag_id':
                    $info['category_tag'] = self::CATEGORY_TAG_MAP[$val];
                    break;
                case 'goods_max_worth':
                    if (bccomp($val, '0.00', 2) == 0) {
                        $info['goods_max_worth'] = '0';
                    }
                    break;
                case 'coupon_text':
                    $coupon = $val ? json_decode($val, true) : [];
                    $info['coupon_link'] = $coupon ? self::getCouponLink($coupon) : '';
                    break;
            }

        }
        $info['current_time'] = time();
        return $info;
    }

    public static function getCouponLink(array $coupon)
    {
        $openAppLink = '';
        if ($coupon && $coupon['link']) {
            $url = $coupon['link'];
            switch ($coupon['type']) {
                case self::COUPON_LINK_TYPE_TB:
                    $result = BizUrl::getTbUrl($url);
                    $openAppLink = $result['open_app_link'];
                    break;
                case self::COUPON_LINK_TYPE_JD:
                    $result = BizUrl::getJdCouponUrl($url);
                    $openAppLink = $result['open_app_link'];
                    break;
            }
        }
        return $openAppLink;
    }

    public static function selectCount($where)
    {
        return self::count($where);
    }

    /**
     * 获取一列的值
     * @param $where
     * @param array $field
     * @return array|bool
     */
    public static function pluck($where, array $field = ['id'])
    {
        return self::select($field, $where);
    }

    public static function insertData($data)
    {
        if (!isset($data['addtime'])) {
            $data['addtime'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::insert($data);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return self::id();
    }

    public static function updateData($data, $where)
    {
        if (!isset($data['edittime'])) {
            $data['edittime'] = date('Y-m-d H:i:s');
        }
        $ret = self::update($data, $where);
        if ($ret->errorCode() !== '00000') {
            return false;
        }

        return true;
    }

    /**
     * 获取一行
     * @param $where
     * @param string|array $field
     * @return array|mixed|null
     */
    public static function first($where, $field = '*')
    {
        $rs = self::get($field, $where);
        if (!$rs) {
            return null;
        }
        if (is_array($field) || $field == '*') {
            $info = self::formatInfo($rs);
        } else {
            $info = $rs;
        }

        return $info;
    }

    /**
     * 批量查询
     * @param $where
     * @param  $field
     * @return array|bool
     */
    public static function all($where, $field = '*')
    {
        $list = [];
        $rs = self::select($field, $where);
        if (!$rs) {
            return $list;
        }
        if (is_array($field) || $field == '*') {
            foreach ($rs as $r) {
                $list[] = self::formatInfo($r);
            }
        } else {
            $list = $rs;
        }
        return $list;
    }

    public static function getConditionByState($activityState)
    {
        $condition = [];
        $now = time();
        switch ($activityState) {
            case self::STATE_DEFAULT://草稿
            case self::STATE_WAIT://待审核
            case self::STATE_NOT_PASS://审核未通过
            case self::STATE_PASS://审核通过
            case self::STATE_DEL://已删除
                $condition['activity_state'] = $activityState;
                break;
            case self::STATE_TO_BE_ONLINE://待上线
                $condition['activity_state'] = self::STATE_PASS;
                $condition['OR'] = [
                    'schedule_start_time' => 0,
                    'schedule_start_time[>]' => $now,
                ];
                break;
            case self::STATE_APPLYING://申请中
                $condition['activity_state'] = self::STATE_PASS;
                $condition['schedule_start_time[<=]'] = $now;
                $condition['schedule_end_time[>]'] = $now;
                break;
            case self::STATE_VERIFY://名单审核中
                $condition['activity_state'] = self::STATE_PASS;
                $condition['schedule_end_time[<=]'] = $now;
                $condition['schedule_end_time[>=]'] = $now - self::VERIFY_USER_TIME;
                break;
            case self::STATE_EXPERIENCING://体验中
                $condition['activity_state'] = self::STATE_PASS;
                $condition['report_num'] = 0;
                $condition['schedule_end_time[>]'] = 0;
                $condition['schedule_end_time[<]'] = $now - self::VERIFY_USER_TIME;
                break;
            case self::STATE_OUTPUT_REPORT://报告已产出
                $condition['activity_state'] = self::STATE_PASS;
                $condition['report_num[>]'] = 0;
                $condition['schedule_end_time[>]'] = 0;
                $condition['schedule_end_time[<]'] = $now - self::VERIFY_USER_TIME;
                break;
        }

        return $condition;
    }

    public static function getCountMaps($map)
    {
        return self::select(['cnt' => Medoo::raw('count(brand_id)'), 'package'], $map);
    }

    public static function getById($id, $format = true)
    {
        $rs = self::get('*', ['id' => $id]);
        $info = !empty($rs) ? $rs : [];
        if ($format) {
            $info = !empty($info) ? self::formatInfo($info) : [];
        }
        return $info;
    }

    /**
     * @param $fansNum
     * @return int
     */
    public static function getUserGrade($fansNum): int
    {
        if ($fansNum <= 149) {
            return self::PACKAGE_FANS_GRADE_DEFAULT;
        }

        if ($fansNum <= 300 && $fansNum >= 150) {
            return self::PACKAGE_FANS_GRADE_A;
        }

        if ($fansNum <= 500 && $fansNum >= 301) {
            return self::PACKAGE_FANS_GRADE_B;
        }

        if ($fansNum <= 1000 && $fansNum >= 501) {
            return self::PACKAGE_FANS_GRADE_C;
        }

        if ($fansNum <= 2000 && $fansNum >= 1001) {
            return self::PACKAGE_FANS_GRADE_D;
        }

        if ($fansNum <= 3000 && $fansNum >= 2001) {
            return self::PACKAGE_FANS_GRADE_E;
        }

        if ($fansNum <= 6000 && $fansNum >= 3001) {
            return self::PACKAGE_FANS_GRADE_F;
        }

        if ($fansNum <= 10000 && $fansNum >= 6001) {
            return self::PACKAGE_FANS_GRADE_G;
        }

        if ($fansNum >= 10001) {
            return self::PACKAGE_FANS_GRADE_H;
        }
    }
}